import {
  BadGatewayException,
  ConflictException,
  HttpException,
  HttpStatus,
  Injectable,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { IdDto } from 'src/common/dto/id.dto';
import { CustomerEntity } from './customer.entity';
import { CustomerSearchDto } from './dto/customer.search.dto';
import { CustomerInsertDto } from './dto/customer.insert.dto';
import { CustomerUpdateDto } from './dto/customer.update.dto';

@Injectable()
export class CustomerService {
  constructor(
    @InjectRepository(CustomerEntity)
    private readonly userCustomerRepository: Repository<CustomerEntity>,
  ) {}

  // 查询用户【根据query条件】
  find(querys: CustomerSearchDto): Promise<CustomerEntity[]> {
    return this.userCustomerRepository.find({ where: querys });
  }

  // 根据id查询
  async findOneById(id: number): Promise<CustomerEntity> {
    try {
      const findUserById: CustomerEntity =
        await this.userCustomerRepository.findOneBy({ id });
      if (!findUserById) {
        throw new HttpException(
          '当前用户id不存在数据库中',
          HttpStatus.INTERNAL_SERVER_ERROR,
        );
      }
      return findUserById;
    } catch (error) {
      throw new HttpException(error.response, error.status);
    }
  }

  // 分页模糊查询
  async getManyAndCount(query: CustomerSearchDto): Promise<any> {
    const data = {
      list: [],
      total: 0,
    };
    try {
      const list = await this.userCustomerRepository
        .createQueryBuilder('customer')
        .where('customer.id like :id')
        .andWhere('customer.area like :area')
        .andWhere('customer.employee_id like :employee_id')
        .setParameters({
          // id
          id: `%${query.id ? query.id : ''}%`,
          // 区域id
          area: `%${query.area ? query.area : ''}%`,
          // 员工id
          employee_id: `%${query.employee_id ? query.employee_id : ''}%`,
        })
        .skip((query.page - 1) * query.pageSize)
        .take(query.pageSize)
        .getManyAndCount();
      data.list = list[0];
      data.total = list[1];
    } catch (error) {
      throw new HttpException('获取列表失败', 502);
    } finally {
      return data;
    }
  }

  // 新增
  async save(data: CustomerInsertDto): Promise<boolean> {
    try {
      // 验证微信是否存在
      const findOneBy: CustomerEntity =
        await this.userCustomerRepository.findOneBy({
          wechat: data.wechat,
        });
      if (findOneBy) {
        throw new ConflictException('微信已存在');
      }
      // 保存用户信息
      const save: CustomerEntity = await this.userCustomerRepository.save(data);
      if (!save) {
        throw new BadGatewayException('入库失败');
      }
      return true;
    } catch (error) {
      throw new HttpException(error.response, error.status);
    }
  }

  // 更新
  async updateById(data: CustomerUpdateDto): Promise<boolean> {
    try {
      // 验证id是否存在
      const findOneById: CustomerEntity =
        await this.userCustomerRepository.findOneBy({
          id: data.id,
        });
      if (!findOneById) {
        throw new HttpException('ID不存在', 400);
      }
      // 更新用户信息
      const update = await this.userCustomerRepository.update(
        { id: data.id },
        data,
      );
      if (!update) {
        throw new HttpException('更新用户失败', 502);
      }
      return true;
    } catch (error) {
      throw new HttpException(error.response, error.status);
    }
  }

  /**
   * 删除
   * @class [IdDto] - 删除验证dto
   */
  async deleteById(data: IdDto): Promise<boolean> {
    try {
      // 删除用户信息
      const deleteById = await this.userCustomerRepository.delete(data);
      if (!deleteById) {
        throw new HttpException('删除用户失败', 502);
      }
      return true;
    } catch (error) {
      throw error;
    }
  }
}
